$(document).ready(function() {
	
	$("#addAppointment").dialog({position: "top",width: 328});
	
	var start;
	var end;
	
	var date = new Date();
	var d = date.getDate();
	var m = date.getMonth();
	var y = date.getFullYear();
	
	var calendar = $('#calendar').fullCalendar({
		header: {
			left: 'prev,next today',
			center: 'title',
			right: 'month,agendaWeek,agendaDay'
		},
		selectable: true,
		selectHelper: true,
		select: function(eStart, eEnd, allDay) {
			start = eStart;
			end = eEnd;
			$("#id").removeAttr("value");
			$("#addAppointment").dialog("open");
			$("#addAppointment").dialog("option","position","center");
			calendar.fullCalendar('unselect');
		},
		editable: true,
		eventClick: function(event, element) {
			start = event.start;
			$("#doctor").val(event.doctor_id);
			$("#patient").val(event.patient_id);
			$("#issue").val(event.issue);
			$("#hour").val( event.hour );
			$("#id").val(event.id);
			$("#minutes").val(event.minute);
			$("#addAppointment").dialog("open");
			$("#addAppointment").dialog("option","position","center");
			
		},
		events: listEvents,
		eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
			var intId = event.id;
			var intPatientId = event.patient_id;
			var intDoctorId = event.doctor_id;
			var strIssue = event.issue;
			var strDate = event.start.getFullYear() + "-" + (parseInt(event.start.getMonth()) + 1) + "-" 
				+ event.start.getDate() + "-" + event.start.getHours() + "-" + event.start.getMinutes();
			
			var listData = {
				action: "save",
				id : intId,
				patientId: intPatientId,
				doctorId: intDoctorId,
				issue: strIssue,
				date: strDate
			};
			
			$.post("/MediFacil/Appointments.do", listData);
		}
	});
	
	$("#addAppointment").dialog("close");
	
	$("#appointmentForm").submit(function(){
		if( ! $(this).valid() )
			return false;
		
		var strPatientName = $("#patient option:selected").html();
		var strIssue = $("#issue").html();
		var intHour = $("#hour").val();
		var intMinute = $("#minutes").val();
		var intDoctorId = $("#doctor").val();
		var intPatientId =  $("#patient").val();
		var strDate = start.getFullYear() + "-" + (parseInt(start.getMonth()) + 1) + "-" + start.getDate() + "-" + intHour + "-" + intMinute;
		
		$("#date").val(strDate);
		
		start.setHours(intHour, intMinute, 0, 0);
		
		
		$(this).find("button:first").attr("disabled","disabled").html("Espere");
		
	});
});